// JWT认证服务

// Token存储键名
const TOKEN_KEY = 'auth_token';
const USER_INFO_KEY = 'user_info';
const REFRESH_TOKEN_KEY = 'refresh_token';
const TOKEN_EXPIRY_KEY = 'token_expiry';

// Token类型
export interface AuthToken {
  access_token: string;
  refresh_token: string;
  expires_in: number;
}

// 用户信息类型
export interface UserInfo {
  id: string;
  username: string;
  email: string;
  role?: string;
  [key: string]: any;
}

/**
 * 保存认证信息
 */
export const saveAuthData = (tokenData: AuthToken, userInfo: UserInfo): void => {
  // 计算token过期时间
  const expiryTime = Date.now() + (tokenData.expires_in * 1000) - 300000; // 提前5分钟过期
  
  localStorage.setItem(TOKEN_KEY, tokenData.access_token);
  localStorage.setItem(REFRESH_TOKEN_KEY, tokenData.refresh_token);
  localStorage.setItem(TOKEN_EXPIRY_KEY, expiryTime.toString());
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo));
};

/**
 * 获取访问令牌
 */
export const getAccessToken = (): string | null => {
  return localStorage.getItem(TOKEN_KEY);
};

/**
 * 获取刷新令牌
 */
export const getRefreshToken = (): string | null => {
  return localStorage.getItem(REFRESH_TOKEN_KEY);
};

/**
 * 检查token是否过期
 */
export const isTokenExpired = (): boolean => {
  const expiryStr = localStorage.getItem(TOKEN_EXPIRY_KEY);
  if (!expiryStr) return true;
  
  const expiryTime = parseInt(expiryStr, 10);
  return Date.now() > expiryTime;
};

/**
 * 获取用户信息
 */
export const getUserInfo = (): UserInfo | null => {
  const userStr = localStorage.getItem(USER_INFO_KEY);
  if (!userStr) return null;
  
  try {
    return JSON.parse(userStr);
  } catch (error) {
    console.error('解析用户信息失败:', error);
    return null;
  }
};

/**
 * 清除认证信息
 */
export const clearAuthData = (): void => {
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(REFRESH_TOKEN_KEY);
  localStorage.removeItem(TOKEN_EXPIRY_KEY);
  localStorage.removeItem(USER_INFO_KEY);
};

/**
 * 检查是否已登录
 */
export const isAuthenticated = (): boolean => {
  const token = getAccessToken();
  return !!token && !isTokenExpired();
};